<?php
// 订单提交接口

class OrderSubmit{
	
	
	public $inside  = null;// 内部接口
	public $outside = null;// 外部接口
	
	
	public function __construct(){
		
	}
		
		
	
	// 下单前权限校验并返回下单数据
	public function Submit_Before_Check($option){
		
		
		$tnum        = $option['tnum'];
		$begintime   = $option['begintime'];  // 游玩时间
        $ordername   = $option['ordername'];  // 取票人姓名
        $ordertel    = $option['ordertel'];   // 取票人手机
        $contacttel  = $option['contacttel']; // 联系人手机
        $remoteorder = $option['remoteorder'];// 远端订单号
        $paymode     = $option['paymode'];    // 支付方式
		$memberSID   = $_SESSION['sid'];
		$apply_did   = $option['apply_did'];  // 上级供应商ID
				
		// 获取产品信息
		$sql = "select l.id as lid,t.id as tid,p.id as pid,p.apply_did,l.title as ltitle,t.title as ttitle,t.tprice,l.p_type,t.buy_limit_low,t.buy_limit_up,t.ddays,f.dhour,t.order_start,t.order_end,f.tourist_info,t.overdue_refund,t.delaydays  from uu_products p left join uu_land l on p.contact_id=l.id left join uu_jq_ticket t on p.id=t.pid left join uu_land_f f on f.pid=p.id where p.p_status=0 and p.apply_limit=1 and p.id=$pid limit 1";
		$GLOBALS['le']->query($sql);
		if(!($p_info = $GLOBALS['le']->fetch_assoc())) throw new Exception('产品未通过审核或已下架');
		
		// 购买限制判断
		if($tnum>$p_info['buy_limit_up'])  throw new Exception('预定不得大于'.$p_info['buy_limit_up']);
		if($tnum<$p_info['buy_limit_low']) throw new Exception('预定不得少于'.$p_info['buy_limit_low']);
		
		
		// 如果是时间段，判断预定日是否在有效期内
		if($p_info['p_type']!='F' && $p_info['order_start']!='' && $p_info['order_end']!='')
		{
			if($p_info['order_end']<$begintime) throw new Exception('预定的游玩时间失效');
		}
		
		// 检测套票子票
        if($p_info['p_type']=='F')
		{
            $chkResult = \pft\Prod\Sale::PackageTicketCheck($this->s, $pid, $fid, $aid, substr($valid_start,0,10), $num);
            if($chkResult['code']!=200) throw new Exception("子票出错，出错信息:{$chkResult['msg']}");
        }
		
		// 购买权限检测
		if($p_info['apply_did']!=$memberSID)
		{
			if($p_info['apply_did'] == $apply_did)
			{
				$sql = "select pids from pft_product_sale_list where aid=$apply_did and fid=$memberSID limit 1";
				$GLOBALS['le']->query($sql);
				if(!$GLOBALS['le']->fetch_assoc() || $GLOBALS['le']->f('status')!=0)
				{
					throw new Exception('无权限购买');
				}
				$pids_a = explode(',', $GLOBALS['le']->f('pids'));
				if($pids_a[0]!='A' && !in_array($pid, $pids_a)) throw new Exception('无权限购买');
			}
			else
			{
				$sql = "select id,pid,sid,active,lvl,status from pft_p_apply_evolute where fid=$memberSID and status=0 sid=$apply_did limit 1";
				$GLOBALS['le']->query($sql);
				if(!$GLOBALS['le']->fetch_assoc() || $GLOBALS['le']->f('status')==1) throw new Exception('无权限购买');
			}
		}
		
		
		// 价格库存判断
		include_once '/var/www/html/new/d/class/abc/PFTCoreAPI.class.php';
		$pStorage = PFTCoreAPI::pStorage($this->inside, $_SESSION['saccount'], $p_info['pid'], $p_info['sapply_did'], $begintime);
		if($pStorage['js']['p']==-1) throw new Exception('出行日期无价格');
		$storage = $pStorage['js']['s'];
        if($storage>-1)
		{
			$rexsml = $this->inside->Dynamic_Storage_Check($p_info['tid'], 1, substr($begintime, 0, 10));
			$simxml = simplexml_load_string($rexsml);
			$dayStorage = explode('|', (string)$simxml->Rec->UUXstr);
			$useStorage = $dayStorage[1];// 已使用库存
			$surplus    = $storage - $useStorage;// 剩余库存
			if($surplus<$tnum) throw new Exception('剩余库存不足');
        }
		

		
		
	}
	
	
	// 下单提交订单
	public function Order_Submit($option)
	{
		
		$result = $inside->__call('Group_Order_Submit', array(
			$params['memberSID'], $params['lid'], $params['tid'], $params['begintime'], 
			$params['endtime'], $params['tprice'], $params['tnum'], $params['totalTprice'],
			$params['ordername'], $params['ordertel'], $params['contacttel'], $params['salerid'],
			$params['sapply_did'], $params['paymode'], $params['ordermode'], $params['remoteorder'],
			$params['assembly'], $params['series'], $params['smsSendWithOrder'], 0, $pcode, $params['idCard']
		));
		
		if($result<100000) throw new Exception('下单接口出错:'.$result);
	}
	
	
	
	
	// 获取产品数据
	public function Get_Product_Information($pid){
		
		$sql = "select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,";
		$sql.= "l.p_type,t.id as tid,t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,";
		$sql.= "t.status,t.storage_open,t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support ";
		$sql.= "from uu_products p left join uu_jq_ticket t on p.id=t.pid left join uu_land l on p.contact_id=l.id ";
		$sql.= "left join uu_land_f f on p.id=f.pid where p.id=$pid limit 1";
		$GLOBALS['le']->query($sql);
		return $GLOBALS['le']->fetch_assoc($sql);
		
	}
		
	
	public function order($option, $aid = 0, $debug = false){
		
		
		
		
		
		
        $s = $this->s;
        $this->option = $option;
        $member = $this->m->memberID;
        $pid = $this->p->pid;

        
        $series = !empty($option['series']) ? $option['series'] : '';
        $tnum = $option['tnum'];
        $remoteorder = $option['remoteorder'];
        $paymode = $option['paymode'];
        //订单类型，normalOrder=>普通订单，linkOrder=>联票订单，packageOrder=>套票订单
        $orderType = 'normalOrder';
        $p_info = $this->p->pInfo();

//        $ptitle = $p_info['ltitle'].$p_info['ttitle'];
        $endtime = ($p_info['delaydays'] - 1) < 0 ? 0 : ($p_info['delaydays'] - 1);
        $time = strtotime($begintime) + $endtime * 24 * 3600;
        $endtime = date("Y-m-d", $time);
        $begintime .= " 00:00:00";
        $endtime   .= " 23:59:59";

        /*产品预订检查*/
        $totalMoney = 0;

        $account = $option['account'] ? $option['account'] : '';
        // 新接口获取
        $tprice = $this->p->tPrice_n($this->sale, $begintime, $aid, '', $account);
        if ($debug) {
            echo $this->sale . '---';
            echo $tprice;
            exit;
        }
        if (is_array($tprice)) {
            throw new DisOrderException($tprice['msg']);
        }
        $totalTprice = $tprice * $tnum;
        $totalMoney += $totalTprice;

        $pcode = 0;
        $ordermode = isset($option['ordermode']) ?
            $option['ordermode'] : $this->ordermode;


        if ($p_info['p_type'] == "B") { /*线路产品额外信息*/
            $playdateStr = explode("-", substr($begintime, 0, 10));
            $playdateStr = substr($playdateStr[0], 2, 2) . $playdateStr[1] . $playdateStr[2];
            $series = preg_replace('/{fck_date}/', $playdateStr, $p_info['series_model']); //团号
            $assembly = abs($_REQUEST['assembly']); //集合地点
        }
//        $proInfos=array();
        $c_infos = array();
        if ($p_info['p_type'] == "C") { //酒店按联票产品下单
            $leavetime = $option['leavetime'];
            $days = ceil((strtotime($leavetime) - strtotime($begintime)) / 24 / 3600);
            $orderType = $days > 1 ? 'linkOrder' : 'normalOrder';
            for ($n = 1; $n < $days; $n++) {
                try {
                    $date = date("Y-m-d", strtotime($begintime) + 3600 * 24 * $n);
                    $starttime = $date . " 00:00:00";
                    // $c_tprice=$cpro->tPrice($member,$begintime,$this->sale);
                    $c_tprice = $this->p->tPrice_n($this->sale, $starttime, $aid,
                        null, $account);
                    // 新接口
                    $c_tnum = $tnum;
                    $endtime = $date . " 23:59:59";
                    $c_infos[] = array("member" => $member,
                        "tprice" => $c_tprice, "tnum" => $c_tnum,
                        "ltitle" => $p_info['ltitle'],
                        "ttitle" => $p_info['ttitle'],
                        "pid" => $p_info['pid'],
                        "lid" => $p_info['lid'],
                        "tid" => $p_info['tid'],
                        "begintime" => $starttime,
                        "endtime" => $date . " 23:59:59",
                        "storage" => $p_info['storage'],
                        "storage_open" => $p_info['storage_open'],
                        "salerid" => $p_info['salerid'],
                        "ordername" => $ordername,
                        "ordertel" => $ordertel,
                        "paymode" => $paymode,
                        "ordermode" => $ordermode,
                        "apply_did" => $p_info['apply_did'],
                        "sapply_did" => $p_info['sapply_did'],
                        "contacttel" => $option['contacttel'],
                    );
                    $totalMoney += $c_tprice * $c_tnum;
                } catch (Exception $e) {
                }
            }
        } elseif ($p_info['p_type'] == "F") { //套票产品
            $pcode = 1;
            $orderType = 'packageOrder';
            //套票判定 Author:CGP
            $bt = substr($begintime, 0, 10);
            $chk_ret = \pft\Prod\Sale::PackageTicketCheck($s, $pid, $member, $aid,
                $bt, $tnum);
            if ($chk_ret['code'] !== 200) {
                $msg = $chk_ret['code'] > 908 ? "子票【{$chk_ret['pid']}】" : '';
                throw new DisOrderException($msg . $chk_ret['msg'] .  $member.'--'.$aid);
            }
        } else {
            /*查看是否存在联票产品，存在的话记录联票产品下单信息*/
            foreach ((array)$option['c_pids'] as $c_pid => $c_tnum) {
                if ($c_tnum > 0) {
                    $orderType = 'linkOrder';
                    $c_pid = abs($c_pid);
                    $c_about = $this->p->pInfo($c_pid);
                    // $c_tprice = $this->p->tPrice($member, $begintime, $this->sale, $c_pid);
                    $c_tprice = $this->p->tPrice_n($this->sale, $begintime, $aid,
                        $c_pid, $account);
                    // 新接口
                    $c_infos[] = array(
                        "member" => $member,
                        "tprice" => $c_tprice,
                        "tnum" => $c_tnum,
                        "ltitle" => $c_about['ltitle'],
                        "ttitle" => $c_about['ttitle'],
                        "pid" => $c_pid,
                        "lid" => $c_about['lid'],
                        "tid" => $c_about['tid'],
                        "begintime" => $begintime,
                        "endtime" => $endtime,
                        "storage" => $c_about['storage'],
                        "storage_open" => $c_about['storage_open'],
                        "salerid" => $c_about['salerid'],
                        "ordername" => $ordername,
                        "ordertel" => $ordertel,
                        "paymode" => $paymode,
                        "ordermode" => $ordermode,
                        "apply_did" => $c_about['apply_did'],
                        "sapply_did" => $c_about['sapply_did'],
                        "contacttel" => $option['contacttel'],
                        "sfz" => $option['sfz'],
                    );
                    $totalMoney += $c_tprice * $c_tnum;
                }
            }
        }

        $smsSendAfterOrder = 0; //下单后发送短信0不发送1发送
        $smsSendWithOrder = 1; //下单并发送短信0发送1不发送
        $no_wx_notify = false;
        $isLnkOrder = count($c_infos); //是否联票订单
        $proInfos = $isLnkOrder ? $c_infos : array(); //联票购买
        $toProvider = 1;
		if($paymode==1){
			$toProvider = 0;
		}
        if ($paymode == 1 || $p_info['sendVoucher'] == 1) {
            //未支付或特殊设置不发送短信
            $no_wx_notify = true;
        } elseif ($isLnkOrder || $p_info['p_type'] == 'C') {
            //联票订单或酒店订单，下单后发送短信
            $smsSendAfterOrder = 1;
        } else {
            //跟随订单一起发送短信
            $smsSendWithOrder = 0;
        }


        $proInfos[] = array(
            "member" => $member,
            "tprice" => $tprice,
            "tnum" => $tnum,
            "ltitle" => $p_info['ltitle'],
            "ttitle" => $p_info['ttitle'],
            "pid" => $p_info['pid'],
            "tid" => $p_info['tid'],
            "begintime" => $begintime,
            "endtime" => $endtime,
            "storage" => $p_info['storage'],
            "storage_open" => $p_info['storage_open'],
            "sapply_did" => $p_info['sapply_did']
        );

        $this->orderCheck($option, $p_info); //预订判定
        //TODO::如果是零售（散客购买),就不判断购买权限，反正都是用零售价
        if (!$this->sale) {
            $this->authCheck($proInfos, $aid); //购买权限判定
        }

        $this->storageCheck($proInfos); //库存判定
        $this->payCheck($totalMoney); //金额判定
	}
	
	
	// 获取指定产品价格 
	// $mode   获取类型 0 分销价 1 零售价 2 都获取
	// $lower  指定日期获取不到价格是否获取最低价
	public function Dynamic_Price_And_Storage($account, $pid, $aid, $today, $mode=2, $get_lower=true){
		
		$clsResult = array('js'=>array('p'=>-1,'s'=>-1), 'ls'=>array('p'=>-1,'s'=>-1));// 返回的价格数组
		if($mode==0 || $mode==2){// 获取结算价
			$simxml = $this->inside->Dynamic_Price_And_Storage($account, $pid, $today, 1, 0, 1, $aid);
			if($simxml==105  && $lower) $simxml = $s->Dynamic_Price_And_Storage($account, $pid, $today, 2, 0, 1, $aid);
			if($simxml==105 || $simxml==1065) return $clsResult;
			$simxml_o = simplexml_load_string($simxml);
			$clsResult['js']['p'] = (string)$simxml_o->Rec->UUsprice/100;
			$clsResult['js']['s'] = (string)$simxml_o->Rec->UUstorage;
		}
		
		if($mode==1 || $mode==2 ){// 获取零售价
			$simxml = $this->inside->Dynamic_Price_And_Storage($account, $pid, $today, 1, 1, 1, $aid);
			if($simxml==105 && $lower) $simxml = $s->Dynamic_Price_And_Storage($account, $pid, $today, 2, 1, 1, $aid);
			if($simxml==105 || $simxml==1065) return $clsResult;
			$simxml_o = simplexml_load_string($simxml);
			$clsResult['ls']['p'] = (string)$simxml_o->Rec->UUsprice/100;
			$clsResult['ls']['s'] = (string)$simxml_o->Rec->UUstorage;
		}
		return $clsResult;
	}
	
}